package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;


    /**
     * 用户注册
     * @param userId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void userRegister(Long userId, Message message, Channel channel){
        try {
            //判断拿到的用户id是不是空的
            if (null != userId) {
                //不为空说明注册成功，进行账户的初始化
                //调用服务层方法
                userAccountService.userRegister(userId);
            }
        } catch (Exception e) {
            //不抛出异常打印一下
            log.error(e.getMessage(),e);
            //可以就是控制一下异常的类型，实现发生网路异常时进行重新发送
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }

        //消费者端手动确认消息，保证消息的成功发送
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
